<template>
  <div ref="container" :style="'height:'+height+'px;'"></div>
</template>

<script>
import echarts from 'echarts'
import _ from 'lodash'

export default {
  name: 'echarts',
  props: {
    option: Object,
    height: {
      type: Number,
      default: 280
    }
  },
  data () {
    return {
      _ec: null
    }
  },
  watch: {
    option () {
      this.render()
    }
  },
  mounted: function () {
    // 当dom元素添加完毕后再render图表，使得能够响应真实的宽度
    this.render()
    this._onresize = function () {
      if (this._ec) {
        this._ec.resize()
      }
    }.bind(this)
    window.addEventListener('resize', this._onresize)
  },
  detached () {
    if (this._ec) {
      this._ec.dispose()
      this._ec = null
    }
    if (this._onresize) {
      window.removeEventListener('resize', this._onresize)
      this._onresize = null
    }
  },
  methods: {
    render () {
      if (this._ec) {
        this._ec.dispose()
        this._ec = null
      }
      // 基于准备好的dom，初始化echarts实例
      this._ec = echarts.init(this.$refs.container)
      // 绘制图表
      if (this.option && this._ec) {
        if (!this.option.series) this.option.series = []
        this._ec.setOption(this.parseOption(this.option))
      }
      this.$emit('rendered', this._ec)
    },

    parseOption (option) {
      if (option.xAxis && option.xAxis.type === 'category' &&
        option.xAxis.data == null) {
        // aAxix 为 category 但是却没有给出categories，手动计算
        var categories = []
        option.series.forEach(function (s) {
          categories = categories.concat(s.data.map(function (item) { return item.name }))
        })
        // categories为所有name的并集
        // if (categories.length && categories[0].split('.').length >= 2) {
          // var splits = categories[0].split('.')
          // todo add
        // }
        categories = _.chain(categories).uniq().sort().value()
        var categoriesXIndex = {} // category 对应的x值的索引
        categories.forEach(function (c, index) {
          categoriesXIndex[c] = index
        })
        var legends = []
        option.series.forEach(function (s) {
          var newData = []
          legends.push(s.name)
          newData.length = categories.length
          s.data.forEach(function (item) {
            newData[categoriesXIndex[item.name]] = item
          })
          s.data = newData
        })
        option.legend = option.legend || {}
        option.legend.data = legends
        option.xAxis.data = categories
      }
      return option
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1 {
  color: #42b983;
}
</style>
